package com.ncr.travel.appmgr.service.mock;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.ncr.travel.appmgr.model.AuditFieldJson;
import com.ncr.travel.appmgr.model.ColumnSpecificationJson;
import com.ncr.travel.appmgr.model.ErrorTextJson;
import com.ncr.travel.appmgr.model.FontOptionsJson;
import com.ncr.travel.appmgr.model.FunctionControlsJson;
import com.ncr.travel.appmgr.model.FunctionJson;
import com.ncr.travel.appmgr.model.GraphicsJson;
import com.ncr.travel.appmgr.model.GraphicsJson.AvailableGraphicsJson;
import com.ncr.travel.appmgr.model.ProductCategoryJson;
import com.ncr.travel.appmgr.model.ProductJson;
import com.ncr.travel.appmgr.model.ThemeInfoJson;
import com.ncr.travel.appmgr.model.RowSpecificationJson;
import com.ncr.travel.appmgr.model.RuleControlsJson;
import com.ncr.travel.appmgr.model.RuleJson;
import com.ncr.travel.appmgr.model.ScreenJson;
import com.ncr.travel.appmgr.model.StationsAuditCriteriaJson;
import com.ncr.travel.appmgr.model.TableDefinitionJson;
import com.ncr.travel.appmgr.model.TextEntryJson;
import com.ncr.travel.appmgr.model.ThemeJson;
import com.ncr.travel.appmgr.model.shared.Alignment;
import com.ncr.travel.appmgr.model.shared.AuditField;
import com.ncr.travel.appmgr.model.shared.AvailableGraphics;
import com.ncr.travel.appmgr.model.shared.Category;
import com.ncr.travel.appmgr.model.shared.ColumnSpecification;
import com.ncr.travel.appmgr.model.shared.FontOptions;
import com.ncr.travel.appmgr.model.shared.Function;
import com.ncr.travel.appmgr.model.shared.FunctionControls;
import com.ncr.travel.appmgr.model.shared.Graphics;
import com.ncr.travel.appmgr.model.shared.Product;
import com.ncr.travel.appmgr.model.shared.ProductCategory;
import com.ncr.travel.appmgr.model.shared.RowSpecification;
import com.ncr.travel.appmgr.model.shared.Rule;
import com.ncr.travel.appmgr.model.shared.RuleControls;
import com.ncr.travel.appmgr.model.shared.Screen;
import com.ncr.travel.appmgr.model.shared.StationsAuditCriteria;
import com.ncr.travel.appmgr.model.shared.TableDefinition;
import com.ncr.travel.appmgr.model.shared.Text;
import com.ncr.travel.appmgr.model.shared.TextEntry;
import com.ncr.travel.appmgr.model.shared.Theme;
import com.ncr.travel.appmgr.service.mapper.AppManagerObjectMapper;
import com.ncr.travel.appmgr.service.model.ScreenConfiguration;

@Component
public class MockDatabase {

	public static final String UUID_KIOSKCHECKIN = "2290af2a-44b8-4c82-b63f-97314aa1d9ef";
	public static final String UUID_WEBCHECKIN = "0244f13b-56e5-4b33-806e-9580baeb6cdf";
	public static final String UUID_RESERVATION = "7aa14355-3f6c-4f56-a2d3-89e92bde4697";
	public static final String UUID_BAGDROP = "f580a9fe-f018-43b6-bb4f-953e98db5414";

	private static final String MOCK_THEME_NAME = "theme1";
	private static final String MOCK_THEME_VERSION = "1.0";
	public static final List<String> PRODUCT_THEME_UUIDS = Arrays.asList(UUID_KIOSKCHECKIN, UUID_WEBCHECKIN,
			UUID_RESERVATION, UUID_BAGDROP);
	private static final String PROJECT_CONFIGURATION = "http://153.71.90.109:8080/appmanager-web/";
	public static final int MULTIPLIER_KIOSKCHECKIN = 1;
	public static final int MULTIPLIER_WEBCHECKIN = 10000;
	public static final int MULTIPLIER_RESERVATION = 20000;
	public static final int MULTIPLIER_BAGDROP = 30000;

	public static final String PATH_KIOSKCHECKIN = "kioskCheck-In";
	public static final String PATH_WEBCHECKIN = "webCheck-In";
	public static final String PATH_RESERVATION = "reservation";
	public static final String PATH_BAGDROP = "bagDrop";

	private final List<Product> products = new ArrayList<Product>();

	private List<ProductCategory> productCategories = new ArrayList<ProductCategory>();
	private final List<Screen> screens = new ArrayList<Screen>();

	private List<String> screenNamesForGlobal = null;
	private List<Integer> screenIdsForGlobal = null;
	private List<String> screenNamesForGlobalErrors = null;
	private List<Integer> screenIdsForGlobalErrors = null;
	private List<String> screenNamesForBaseCheckIn = null;
	private List<Integer> screenIdsForBaseCheckIn = null;
	private List<String> screenNamesForInternationsDocEntry = null;
	private List<Integer> screenIdsForInternationsDocEntry = null;
	private List<String> screenNamesForFeeModule = null;
	private List<Integer> screenIdsForFeeModule = null;
	private List<String> screenNamesForNonRevenueModule = null;
	private List<Integer> screenIdsForNonRevenueModule = null;
	private List<String> screenNamesForAgentAssist = null;
	private List<Integer> screenIdsForAgentAssist = null;

	private List<String> screenNamesForBaseCheckInSelectPassenger = null;

	private List<Integer> screenIdsForBaseCheckInSelectPassenger;

	private List<String> screenNamesForBaseCheckInSecureFlight;

	private List<Integer> screenIdsForBaseCheckInSecureFlight;

	private List<String> screenNamesForBaseCheckInBaggage;

	private List<Integer> screenIdsForBaseCheckInBaggage;

	private List<String> screenNamesForFeeModuleBaggageFee;

	private List<Integer> screenIdsForFeeModuleBaggageFee;

	private List<String> screenNamesForFeeModulePremiumSeating;

	private List<Integer> screenIdsForFeeModulePremiumSeating;

	private List<String> screenNamesForBaseCheckInThankYou;
	private List<Integer> screenIdsForBaseCheckInThankYou;

	private final Map<Integer, ScreenConfiguration> screenConfigurations = new HashMap<Integer, ScreenConfiguration>();

	private Map<Integer, List<Graphics>> screenGraphicsDictionary;

	String imagesRootDirName = "\\\\127.0.0.1\\C$\\images";
	String logoImagesUrl = "http://153.71.90.109:8080/appmanager-imageprovider/images/logo/";
	String findByOptionsImagesUrl = "http://153.71.90.109:8080/appmanager-imageprovider/images/findbyoptions/";

	@Autowired
	private AppManagerObjectMapper mapper;

	public MockDatabase() {
		super();
	}

	@PostConstruct
	public void initializeMockDatabase() {
		populateScreenNames();
		populateProductCategories();
		List<ScreenConfiguration> screenConfigsForKioskCheckin = populatescreenConfigsForKioskCheckIn();
		List<ScreenConfiguration> screenConfigsForWebCheckin = populatescreenConfigsForWebCheckIn(screenConfigsForKioskCheckin);
		List<ScreenConfiguration> screenConfigsForReservation = populatescreenConfigsForReservationOrTicketing(screenConfigsForKioskCheckin);
		List<ScreenConfiguration> screenConfigsForBagDrop = populatescreenConfigsForBagDrop(screenConfigsForKioskCheckin);

		List<ScreenConfiguration> screenConfigs = new ArrayList<ScreenConfiguration>();
		screenConfigs.addAll(screenConfigsForKioskCheckin);
		screenConfigs.addAll(screenConfigsForWebCheckin);
		screenConfigs.addAll(screenConfigsForReservation);
		screenConfigs.addAll(screenConfigsForBagDrop);

		for (ScreenConfiguration screenConfig : screenConfigs) {
			screenConfigurations.put(screenConfig.getId(), screenConfig);
		}
	}

	public Theme getTheme() {
		Theme theme = new ThemeJson();
		theme.setId(UUID_KIOSKCHECKIN);
		theme.setName(MOCK_THEME_NAME);
		theme.setVersion(MOCK_THEME_VERSION);
		ThemeInfoJson themeInfo = new ThemeInfoJson();
		themeInfo.setProperty("styleSheet", "/themes/cool/style.css");
		themeInfo.setProperty("background", "/themes/cool/img/coolBg.jpg");
		themeInfo.setProperty("script", "/themes/cool/testscript.js");
		theme.setThemeInfo(themeInfo);
		return theme;
	}

	public ScreenConfiguration getScreenConfiguration(int screenId) throws Exception {

		// /this will no inter work all by itself. Part of the
		// screen configuration is coming from disk
		// return screenConfigurations.get(screenId);

		// new way to update the ScreenConfiguration, which is part
		// hardcoded and part comes from the xml disk files

		// GET THE HARD CODED PARTS FROM THE COLLECTION FOR SCREENCONFIGS
		ScreenConfiguration configuration = screenConfigurations.get(screenId);

		if (configuration != null) {

			// Load the lists of functions (xml/dynamic deserialized from disk)
			List<Function> functions = getFunctionsByScreenId(screenId);

			// update the screen configuration's hard coded functions with the
			// disk versions
			if (functions != null && !functions.isEmpty()) {
				configuration.setFunctions(functions);
			}

			// update the screen configuration's hard coded rules with the
			// disk versions
			List<Rule> rules = getRulesByScreenIdFromXML(screenId);
			if (rules != null && !rules.isEmpty()) {
				configuration.setRules(rules);
			}

			// update the screen configuration's hard coded text with the
			// disk versions
			List<Text> text = getTextByScreenId(screenId);
			if (text != null && !text.isEmpty()) {
				configuration.setText(text);
			}

		}

		// return the resulting hybrid object
		return configuration;

	}

	private List<ScreenConfiguration> populatescreenConfigsForKioskCheckIn() {
		List<ScreenConfiguration> screenConfigsForKioskCheckIn = new ArrayList<ScreenConfiguration>();
		try {

			/**************** MOCK SCREEN CONFIGS FOR KIOSK CHECK-IN STARTS HERE ***************************/
			ScreenConfiguration config = new ScreenConfiguration(9999, "Mock Screen", (PROJECT_CONFIGURATION
					+ PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 9999));
			config.setText(getTextByScreenId(config.getId()));
			config.setGraphics(getGraphicsByScreenId(config.getId()));
			// config.setFunctions(getFunctionsByScreenId(config.getId()));
			config.setRules(getRulesByScreenId(config.getId()));

			ScreenConfiguration config1 = new ScreenConfiguration(101, "Logo", (PROJECT_CONFIGURATION
					+ PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 101));
			config1.setGraphics(getGraphicsByScreenId(config1.getId()));

			ScreenConfiguration config2 = new ScreenConfiguration(
					244,
					"Special Service Requests Code",
					(PROJECT_CONFIGURATION + PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 244));
			// config2.setText(getTextByScreenId(config2.getId()));
			config2.setGraphics(getGraphicsByScreenId(config2.getId()));
			// config2.setFunctions(getFunctionsByScreenId(config2.getId()));
			config2.setRules(getRulesByScreenId(config2.getId()));

			ScreenConfiguration config3 = new ScreenConfiguration(444, "Offer", (PROJECT_CONFIGURATION
					+ PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 444));
			// config3.setText(getTextByScreenId(config3.getId()));
			config3.setGraphics(getGraphicsByScreenId(config3.getId()));

			config3.setFunctions(getFunctionsByScreenId(config3.getId()));
			config3.setRules(getRulesByScreenId(config3.getId()));

			screenConfigsForKioskCheckIn.add(config);
			screenConfigsForKioskCheckIn.add(config2);
			screenConfigsForKioskCheckIn.add(config3);

			config = new ScreenConfiguration(202, "Attract Screen", (PROJECT_CONFIGURATION + PATH_KIOSKCHECKIN
					+ "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 202));
			config.setText(getTextByScreenId(config.getId()));
			config.setGraphics(getGraphicsByScreenId(config.getId()));
			// config.setFunctions(getFunctionsByScreenId(config.getId()));
			config.setRules(getRulesByScreenId(config.getId()));
			screenConfigsForKioskCheckIn.add(config);

			config = new ScreenConfiguration(278, "Thank You-1", (PROJECT_CONFIGURATION + PATH_KIOSKCHECKIN
					+ "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 278));
			config.setText(getTextByScreenId(config.getId()));
			config.setGraphics(getGraphicsByScreenId(config.getId()));

			config.setFunctions(getFunctionsByScreenId(config.getId()));
			config.setRules(getRulesByScreenId(config.getId()));
			screenConfigsForKioskCheckIn.add(config);

			config = new ScreenConfiguration(1410, "Check-In", (PROJECT_CONFIGURATION + PATH_KIOSKCHECKIN
					+ "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 1410));
			config.setText(getTextByScreenId(config.getId()));
			config.setGraphics(getGraphicsByScreenId(config.getId()));
			// config.setFunctions(getFunctionsByScreenId(config.getId()));
			config.setRules(getRulesByScreenId(config.getId()));
			screenConfigsForKioskCheckIn.add(config);

			ScreenConfiguration config4 = new ScreenConfiguration(241, "Add Mileage Plan", (PROJECT_CONFIGURATION
					+ PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 241));
			config4.setFunctions(getFunctionsByScreenId(config4.getId()));
			config4.setRules(getRulesByScreenId(config4.getId()));

			ScreenConfiguration config7 = new ScreenConfiguration(
					251,
					"Secure Flight Data Entry",
					(PROJECT_CONFIGURATION + PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 251));

			config7.setFunctions(getFunctionsByScreenId(config7.getId()));

			ScreenConfiguration config8 = new ScreenConfiguration(203, "Find By Options", (PROJECT_CONFIGURATION
					+ PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 203));
			config8.setGraphics(getGraphicsByScreenId(config8.getId()));

			ScreenConfiguration config9 = new ScreenConfiguration(102, "Language Options", (PROJECT_CONFIGURATION
					+ PATH_KIOSKCHECKIN + "?themeUUID=" + UUID_KIOSKCHECKIN + "&screenID=" + 102));
			config9.setFunctions(getFunctionsByScreenId(config9.getId()));

			// configuration for more screens

			screenConfigsForKioskCheckIn.add(config1);
			screenConfigsForKioskCheckIn.add(config4);
			screenConfigsForKioskCheckIn.add(config7);
			screenConfigsForKioskCheckIn.add(config8);
			screenConfigsForKioskCheckIn.add(config9);

			/**************** MOCK SCREEN CONFIGS FOR KIOSK CHECK-IN ENDS HERE ***************************/

		} catch (Exception e) {
			e.printStackTrace();
		}
		return screenConfigsForKioskCheckIn;
	}

	private List<ScreenConfiguration> populatescreenConfigsForWebCheckIn(List<ScreenConfiguration> configsKioskCheckIn) {
		/**************** MOCK SCREEN CONFIGS FOR WEB CHECK-IN STARTS HERE ***************************/
		List<ScreenConfiguration> screenConfigsForWebCheckIn = new ArrayList<ScreenConfiguration>();
		for (ScreenConfiguration sourceConfig : configsKioskCheckIn) {
			try {
				ScreenConfiguration configForWebCheckIn = new ScreenConfiguration();
				configForWebCheckIn.setId(sourceConfig.getId() + MULTIPLIER_WEBCHECKIN);
				configForWebCheckIn.setUrl((PROJECT_CONFIGURATION + PATH_WEBCHECKIN + "?themeUUID=" + UUID_WEBCHECKIN
						+ "&screenID=" + configForWebCheckIn.getId()));
				configForWebCheckIn.setName(sourceConfig.getName());
				configForWebCheckIn.setKey(sourceConfig.getName());
				configForWebCheckIn.setText(getTextByScreenId(configForWebCheckIn.getId()));
				configForWebCheckIn.setGraphics(getGraphicsByScreenId(configForWebCheckIn.getId()));

				configForWebCheckIn.setFunctions(getFunctionsByScreenId(configForWebCheckIn.getId()));
				configForWebCheckIn.setRules(getRulesByScreenId(configForWebCheckIn.getId()));
				screenConfigsForWebCheckIn.add(configForWebCheckIn);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return screenConfigsForWebCheckIn;
		/**************** MOCK SCREEN CONFIGS FOR WEB CHECK-IN ENDS HERE ***************************/
	}

	private List<ScreenConfiguration> populatescreenConfigsForReservationOrTicketing(
			List<ScreenConfiguration> configsKioskCheckIn) {
		/**************** MOCK SCREEN CONFIGS FOR RESERVATION CHECK-IN STARTS HERE ***************************/
		List<ScreenConfiguration> screenConfigsForReservation = new ArrayList<ScreenConfiguration>();
		for (ScreenConfiguration sourceConfig : configsKioskCheckIn) {
			try {
				ScreenConfiguration configForReservation = new ScreenConfiguration();
				configForReservation.setId(sourceConfig.getId() + MULTIPLIER_RESERVATION);
				configForReservation.setUrl((PROJECT_CONFIGURATION + PATH_RESERVATION + "?themeUUID="
						+ UUID_RESERVATION + "&screenID=" + configForReservation.getId()));
				configForReservation.setName(sourceConfig.getName());
				configForReservation.setKey(sourceConfig.getName());
				configForReservation.setText(getTextByScreenId(configForReservation.getId()));
				configForReservation.setGraphics(getGraphicsByScreenId(configForReservation.getId()));

				configForReservation.setFunctions(getFunctionsByScreenId(configForReservation.getId()));
				configForReservation.setRules(getRulesByScreenId(configForReservation.getId()));
				screenConfigsForReservation.add(configForReservation);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return screenConfigsForReservation;
		/**************** MOCK SCREEN CONFIGS FOR RESERVATION CHECK-IN ENDS HERE ***************************/
	}

	private List<ScreenConfiguration> populatescreenConfigsForBagDrop(List<ScreenConfiguration> configsKioskCheckIn) {
		/**************** MOCK SCREEN CONFIGS FOR BAGDROP CHECK-IN STARTS HERE ***************************/
		List<ScreenConfiguration> screenConfigsForBagDrop = new ArrayList<ScreenConfiguration>();
		for (ScreenConfiguration sourceConfig : configsKioskCheckIn) {
			try {
				ScreenConfiguration configForBagDrop = new ScreenConfiguration();
				configForBagDrop.setId(sourceConfig.getId() + MULTIPLIER_BAGDROP);
				configForBagDrop.setUrl((PROJECT_CONFIGURATION + PATH_BAGDROP + "?themeUUID=" + UUID_BAGDROP
						+ "&screenID=" + configForBagDrop.getId()));
				configForBagDrop.setName(sourceConfig.getName());
				configForBagDrop.setKey(sourceConfig.getName());
				configForBagDrop.setText(getTextByScreenId(configForBagDrop.getId()));
				configForBagDrop.setGraphics(getGraphicsByScreenId(configForBagDrop.getId()));

				configForBagDrop.setFunctions(getFunctionsByScreenId(configForBagDrop.getId()));
				configForBagDrop.setRules(getRulesByScreenId(configForBagDrop.getId()));
				screenConfigsForBagDrop.add(configForBagDrop);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return screenConfigsForBagDrop;
		/**************** MOCK SCREEN CONFIGS FOR BAGDROP CHECK-IN ENDS HERE ***************************/
	}

	private List<Text> getMockScreenText(int screenId) {
		List<Text> textEntries = new ArrayList<Text>();
		if (screenId == 9999) {
			// Mock screen text configurations for testing
			FontOptionsJson fontOptions = new FontOptionsJson();
			fontOptions.setColor("#000000");
			fontOptions.setStyle("Default");
			fontOptions.setSize(11);
			fontOptions.setAlignment(Alignment.LEFT);

			textEntries = new ArrayList<Text>();
			TextEntryJson textEntry = new TextEntryJson();
			textEntry.setId(1001);
			textEntry.setName("text.welcome");
			textEntry.setValue("Welcome to our self-service check-in kiosk");
			textEntry.setCategory(Category.LABEL);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);
		} else if (screenId == 444 || screenId == 10444 || screenId == 20444 || screenId == 30444) {
			// Text configurations for FeeModulePremiumSeating-Offer screen

		} else if (screenId == 244 || screenId == 10244 || screenId == 20244 || screenId == 30244) {
			// Text configurations for BaseCheckInSelectPassenger - Special
			// Service Requests Code

		} else if (screenId == 202 || screenId == 10202 || screenId == 20202 || screenId == 30202) {
			// Text configurations forBaseCheckIn - Attract Screen
			textEntries = new ArrayList<Text>();
			TextEntry textEntry = new TextEntryJson();
			textEntry.setId(1002);
			textEntry.setName("text.welcome");
			textEntry.setValue("Welcome to our self-service check-in kiosk");
			textEntry.setCategory(Category.LABEL);

			FontOptions fontOptions = new FontOptionsJson();
			fontOptions.setColor("#5778CA");
			fontOptions.setStyle("Bold");
			fontOptions.setSize(12);
			fontOptions.setAlignment(Alignment.LEFT);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);

			textEntry = new TextEntryJson();
			textEntry.setId(1003);
			textEntry.setName("text.start");
			textEntry.setValue("Start Check in");
			textEntry.setCategory(Category.BUTTON);
			fontOptions = new FontOptionsJson();
			fontOptions.setColor("#ACE3FC");
			fontOptions.setStyle("Default");
			fontOptions.setSize(14);
			fontOptions.setAlignment(Alignment.RIGHT);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);

			textEntry = new TextEntryJson();
			textEntry.setId(1004);
			textEntry.setName("text.language");
			textEntry.setValue("Spanish");
			textEntry.setCategory(Category.BUTTON);
			fontOptions = new FontOptionsJson();
			fontOptions.setColor("#FCF86F");
			fontOptions.setStyle("Italic");
			fontOptions.setSize(11);
			fontOptions.setAlignment(Alignment.JUSTIFY);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);
		} else if (screenId == 278 || screenId == 10278 || screenId == 20278 || screenId == 30278) {
			FontOptions fontOptions = new FontOptionsJson();
			fontOptions.setColor("#ACE3FC");
			fontOptions.setStyle("Default");
			fontOptions.setSize(14);
			fontOptions.setAlignment(Alignment.RIGHT);

			textEntries = new ArrayList<Text>();
			TextEntryJson textEntry = new TextEntryJson();
			textEntry.setId(1005);
			textEntry.setName("text.thankyou");
			textEntry.setValue("Thank you for flying with us!");
			textEntry.setCategory(Category.LABEL);
			textEntry.setMultiLine(false);
			fontOptions.setColor("#FCF86F");
			fontOptions.setStyle("Italic");
			fontOptions.setSize(11);
			fontOptions.setAlignment(Alignment.JUSTIFY);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);

			textEntry = new TextEntryJson();
			textEntry.setId(1006);
			textEntry.setName("text.checkInFor");
			textEntry.setValue("You are now checkedin for:");
			textEntry.setCategory(Category.LABEL);
			textEntry.setMultiLine(true);
			fontOptions.setColor("#5778CA");
			fontOptions.setStyle("Bold");
			fontOptions.setSize(12);
			fontOptions.setAlignment(Alignment.LEFT);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);

			textEntry = new TextEntryJson();
			textEntry.setId(1007);
			textEntry.setName("text.wait");
			textEntry
					.setValue("Please wait while we print your boarding documents and receipts (Printing 2 of 4 item(s))");
			textEntry.setCategory(Category.LABEL);
			textEntry.setMultiLine(false);
			fontOptions.setColor("#FBF304");
			fontOptions.setStyle("Underline");
			fontOptions.setSize(10);
			fontOptions.setAlignment(Alignment.CENTER);
			textEntry.setFontOptions(fontOptions);
			textEntries.add(textEntry);
		} else if (screenId == 1410 || screenId == 11410 || screenId == 21410 || screenId == 31410) {

			textEntries = new ArrayList<Text>();

			FontOptionsJson fontOptions = new FontOptionsJson();
			fontOptions.setColor("#5778CA");
			fontOptions.setStyle("Bold");
			fontOptions.setSize(12);
			fontOptions.setAlignment(Alignment.LEFT);

			ErrorTextJson eCode = new ErrorTextJson();
			eCode.setCategory(Category.LABEL);
			eCode.setCode(300);
			eCode.setMessage("Check In Failed.");
			eCode.setFontOptions(fontOptions);
			eCode.setMultiLine(false);
			textEntries.add(eCode);

			fontOptions = new FontOptionsJson();
			fontOptions.setColor("#ACE3FC");
			fontOptions.setStyle("Default");
			fontOptions.setSize(14);
			fontOptions.setAlignment(Alignment.RIGHT);

			eCode = new ErrorTextJson();
			eCode.setCategory(Category.LABEL);
			eCode.setCode(301);
			eCode.setMessage("There are too many bags on the PNR to check-in.");
			eCode.setFontOptions(fontOptions);
			eCode.setMultiLine(false);
			textEntries.add(eCode);

			fontOptions = new FontOptionsJson();
			fontOptions.setColor("#FCF86F");
			fontOptions.setStyle("Italic");
			fontOptions.setSize(11);
			fontOptions.setAlignment(Alignment.JUSTIFY);

			eCode = new ErrorTextJson();
			eCode.setCategory(Category.LABEL);
			eCode.setCode(302);
			eCode.setMessage("Unable to add bags to the PNR.");
			eCode.setFontOptions(fontOptions);
			eCode.setMultiLine(false);
			textEntries.add(eCode);

			fontOptions = new FontOptionsJson();
			fontOptions.setColor("#7891F5");
			fontOptions.setStyle("Underline");
			fontOptions.setSize(10);
			fontOptions.setAlignment(Alignment.CENTER);

			eCode = new ErrorTextJson();
			eCode.setCategory(Category.LABEL);
			eCode.setCode(303);
			eCode.setMessage("One or more passengers are on the TSA Watch list.");
			eCode.setFontOptions(fontOptions);
			eCode.setMultiLine(false);
			textEntries.add(eCode);
		}
		return textEntries;
	}

	private List<Graphics> getGraphicsByScreenId(int screenId) {
		List<Graphics> graphicItems = null;

		if (screenGraphicsDictionary == null) {
			screenGraphicsDictionary = new HashMap<Integer, List<Graphics>>();
		}

		try {
			if (screenId == 101 || screenId == 10101 || screenId == 20101 || screenId == 30101) {

				if (!screenGraphicsDictionary.containsKey(screenId)) {
					graphicItems = getLogoGraphics();

					screenGraphicsDictionary.put(screenId, graphicItems);
				} else {
					graphicItems = screenGraphicsDictionary.get(screenId);
				}

			}
			if (screenId == 203 || screenId == 10203 || screenId == 20203 || screenId == 30203) {

				if (!screenGraphicsDictionary.containsKey(screenId)) {
					graphicItems = getFindByOptionsGraphics();// GetFindByOptionsGraphicsFromCP();
					screenGraphicsDictionary.put(screenId, graphicItems);
				} else {
					graphicItems = screenGraphicsDictionary.get(screenId);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return graphicItems;
	}

	private List<Graphics> getLogoGraphics() {

		String logoDirName = this.imagesRootDirName + "\\Logo";

		File rootDir = new File(logoDirName);

		List<Graphics> graphicItems = new ArrayList<Graphics>();

		String testImageNames[] = { "Logo" };

		// get the Logo image names.
		String imageFiles[] = rootDir.list();

		int idx = 1010;

		GraphicsJson newGraphics = new GraphicsJson();
		newGraphics.setId(idx);
		newGraphics.setName(testImageNames[0]);

		List<AvailableGraphics> images = new ArrayList<AvailableGraphics>();

		if (imageFiles != null) {
			int jdx = 10100;
			for (String imageFile : imageFiles) {

				System.out.println(imageFile);

				int mid = imageFile.lastIndexOf(".");

				String ext = imageFile.substring(mid + 1, imageFile.length());

				if (!ext.equalsIgnoreCase("db")) {

					AvailableGraphicsJson availableGraphics = new AvailableGraphicsJson();

					if (jdx == 10100) {
						availableGraphics.setSelected(true);
					} else {
						availableGraphics.setSelected(false);
					}

					jdx++;

					System.out.println(this.logoImagesUrl + imageFile);
					/* .println(rootDir.getAbsolutePath() + "\\" + imageFile); */

					availableGraphics.setUrl(this.logoImagesUrl + imageFile);
					/*
					 * availableGraphics.setUrl(rootDir.getAbsolutePath() + "\\" +
					 * imageFile);
					 */

					images.add(availableGraphics);
				} else {
					System.out.println("Excluded " + imageFile);
				}

			}
		}

		newGraphics.setAvailableGraphics(images);

		graphicItems.add(newGraphics);

		return graphicItems;

	}

	/**
	 * @return list of GraphicsJson items.
	 */
	private List<Graphics> getFindByOptionsGraphics() {

		String dirname = this.imagesRootDirName + "\\FindByOptions";

		File rootDir = new File(dirname);

		String subDirectories[] = rootDir.list();

		List<Graphics> graphicItems = new ArrayList<Graphics>();

		String testImageNames[] = { "ConfirmationNumber", "DestinationCity", "E-TicketNumber", "InsertCreditCard",
				"ScanBarcode", "SwipePassport" };

		int idx = 2030;

		int i = 0;
		for (String imageName : testImageNames) {

			GraphicsJson newGraphics = new GraphicsJson();
			newGraphics.setId(idx);

			newGraphics.setName(imageName);

			String subDirPath = dirname + "\\" + subDirectories[i];

			System.out.println(subDirPath);

			File subDir = new File(subDirPath);

			String imageFiles[] = subDir.list();

			List<AvailableGraphics> images = new ArrayList<AvailableGraphics>();
			int jdx = 20300;
			for (String imageFile : imageFiles) {

				System.out.println(imageFile);

				int mid = imageFile.lastIndexOf(".");

				String ext = imageFile.substring(mid + 1, imageFile.length());

				if (!ext.equalsIgnoreCase("db")) {

					AvailableGraphicsJson availableGraphics = new AvailableGraphicsJson();

					if (jdx == 20300) {
						availableGraphics.setSelected(true);
					} else {
						availableGraphics.setSelected(false);
					}

					jdx++;
					// this.findByOptionsImagesUrl + imageName + "/" + imageFile

					System.out.println(this.findByOptionsImagesUrl + imageName.toLowerCase() + "/" + imageFile);

					availableGraphics.setUrl(this.findByOptionsImagesUrl + imageName.toLowerCase() + "/" + imageFile);
					/*
					 * System.out.println(subDirPath + "\\" + imageFile);
					 * 
					 * availableGraphics.setUrl(subDirPath + "\\" + imageFile);
					 */

					images.add(availableGraphics);
				} else {
					System.out.println("Excluded " + imageFile);
				}

			}

			newGraphics.setAvailableGraphics(images);

			graphicItems.add(newGraphics);

			idx++;
			i++;
		}

		return graphicItems;

	}

	// TODO: Integration for Madhavi configuration settings
	private List<Function> getFunctionsByScreenId(int screenId) throws Exception {

		// make call to ensure we have functions persisted to disk
		this.ensureMockScreenFunctionDataExists(screenId);

		// return functions by screen from disk
		return this.fetchFunctionsFromDisk(screenId);

		// return getMockScreenFunctions(screenId);

	}

	private List<Text> getTextByScreenId(int screenId) throws Exception {

		// make call to ensure we have text persisted to disk
		this.ensureMockScreenTextDataExists(screenId);

		// return text by screen from disk
		return this.fetchTextFromDisk(screenId);
	}

	private List<Rule> getRulesByScreenIdFromXML(int screenId) throws Exception {

		// make call to ensure we have functions persisted to disk
		this.ensureMockScreenRuleDataExists(screenId);

		// return functions by screen from disk
		return this.fetchRulesFromDisk(screenId);

		// return getMockScreenFunctions(screenId);

	}

	private List<Function> getMockScreenFunctions(int screenId) {

		List<Function> functions = new ArrayList<Function>();

		if (screenId == 241 || screenId == 251 || screenId == 10241 || screenId == 10251 || screenId == 20241
				|| screenId == 20251 || screenId == 30241 || screenId == 30251) {

			functions = new ArrayList<Function>();

			FunctionJson function = new FunctionJson();

			function.setId(3001);
			function.setName("Redress Number");
			function.setActive(false);

			FunctionControls functionControls = new FunctionControlsJson();

			functionControls.setIsRadioEnabled(false);
			functionControls.setIsSelectEnabled(false);

			StationsAuditCriteria auditCriteria = new StationsAuditCriteriaJson();
			auditCriteria.setAllStations(true);

			List<AuditField> stations = new ArrayList<AuditField>();
			AuditFieldJson station = new AuditFieldJson("ATL", false);
			stations.add(station);
			station = new AuditFieldJson("SEA", false);
			stations.add(station);
			station = new AuditFieldJson("MCO", false);
			stations.add(station);
			station = new AuditFieldJson("JFK", false);
			stations.add(station);
			auditCriteria.setStations(stations);

			function.setAuditCriteria(auditCriteria);

			function.setFunctionControls(functionControls);

			functions.add(function);
			FunctionJson function2 = new FunctionJson();
			function2.setId(3002);
			function2.setName("Known Travelers");
			function2.setActive(true);

			FunctionControls functionControls2 = new FunctionControlsJson();

			functionControls2.setIsRadioEnabled(false);
			functionControls2.setIsSelectEnabled(false);

			StationsAuditCriteria auditCriteria1 = new StationsAuditCriteriaJson();
			auditCriteria1.setAllStations(true);

			List<AuditField> stationsList = new ArrayList<AuditField>();
			AuditFieldJson station1 = new AuditFieldJson("ABC", false);
			stationsList.add(station1);
			station1 = new AuditFieldJson("DEF", false);
			stationsList.add(station1);
			station1 = new AuditFieldJson("GHI", true);
			stationsList.add(station1);
			station1 = new AuditFieldJson("JKL", false);
			stationsList.add(station1);
			auditCriteria1.setStations(stationsList);

			function2.setAuditCriteria(auditCriteria1);

			function2.setFunctionControls(functionControls2);

			functions.add(function2);

		}

		else if (screenId == 444 || screenId == 10444 || screenId == 20444 || screenId == 30444) {

			functions = new ArrayList<Function>();

			FunctionJson function = new FunctionJson();
			function.setId(3003);
			function.setName("Offer");
			function.setActive(true);

			FunctionControls functionControls = new FunctionControlsJson();

			functionControls.setIsRadioEnabled(true);
			functionControls.setIsSelectEnabled(true);

			StationsAuditCriteria auditCriteria = new StationsAuditCriteriaJson();
			auditCriteria.setAllStations(true);

			List<AuditField> stations = new ArrayList<AuditField>();
			AuditFieldJson station = new AuditFieldJson("PAQ", false);
			stations.add(station);
			station = new AuditFieldJson("ABC", false);
			stations.add(station);
			station = new AuditFieldJson("DEF", true);
			stations.add(station);
			station = new AuditFieldJson("JFK", false);
			stations.add(station);
			auditCriteria.setStations(stations);
			auditCriteria.setAuditCriteriaType("STATIONS");

			function.setAuditCriteria(auditCriteria);

			function.setFunctionControls(functionControls);
			functions.add(function);

		} else if (screenId == 278 || screenId == 10278 || screenId == 20278 || screenId == 30278) {
			functions = new ArrayList<Function>();

			FunctionJson function = new FunctionJson();

			function.setId(3004);
			function.setName("Promo Ads");
			function.setActive(true);

			FunctionControls functionControls = new FunctionControlsJson();
			functionControls.setIsRadioEnabled(false);
			functionControls.setIsSelectEnabled(false);

			StationsAuditCriteria auditCriteria = new StationsAuditCriteriaJson();
			auditCriteria.setAllStations(false);

			List<AuditField> stations = new ArrayList<AuditField>();
			AuditFieldJson station = new AuditFieldJson("ATL", false);
			stations.add(station);
			station = new AuditFieldJson("SEA", false);
			stations.add(station);
			station = new AuditFieldJson("MCO", false);
			stations.add(station);
			station = new AuditFieldJson("JFK", false);
			stations.add(station);
			auditCriteria.setStations(stations);

			function.setAuditCriteria(auditCriteria);

			function.setFunctionControls(functionControls);

			functions.add(function);

		} else if (screenId == 102 || screenId == 10102 || screenId == 20102 || screenId == 30102) {

			functions = new ArrayList<Function>();

			FunctionJson function1 = new FunctionJson();
			function1.setId(3005);
			function1.setName("English");
			function1.setActive(false);
			functions.add(function1);

			FunctionJson function2 = new FunctionJson();
			function2.setId(3006);
			function2.setName("French");
			function2.setActive(false);
			functions.add(function2);

			FunctionJson function3 = new FunctionJson();
			function3.setId(3007);
			function3.setName("Spanish");
			function3.setActive(true);
			functions.add(function3);

			FunctionJson function4 = new FunctionJson();
			function4.setId(3008);
			function4.setName("Arabic");
			function4.setActive(false);
			functions.add(function4);

			FunctionJson function5 = new FunctionJson();
			function5.setId(3009);
			function5.setName("Hindi");
			function5.setActive(false);
			functions.add(function5);

			FunctionJson function6 = new FunctionJson();
			function6.setId(3010);
			function6.setName("German");
			function6.setActive(false);
			functions.add(function6);

			FunctionJson function7 = new FunctionJson();
			function7.setId(3011);
			function7.setName("Russian");
			function7.setActive(false);
			functions.add(function7);

			FunctionJson function8 = new FunctionJson();
			function8.setId(3012);
			function8.setName("ABCD");
			function8.setActive(false);
			functions.add(function8);

			FunctionJson function9 = new FunctionJson();
			function9.setId(3013);
			function9.setName("DEFG");
			function9.setActive(false);
			functions.add(function9);

			FunctionJson function10 = new FunctionJson();
			function10.setId(3014);
			function10.setName("HIJK");
			function10.setActive(false);
			functions.add(function10);

			FunctionJson function11 = new FunctionJson();
			function11.setId(3015);
			function11.setName("LMNO");
			function11.setActive(false);
			functions.add(function11);

			FunctionJson function12 = new FunctionJson();
			function12.setId(3016);
			function12.setName("PQRS");
			function12.setActive(false);
			functions.add(function12);

			FunctionJson function13 = new FunctionJson();
			function13.setId(3017);
			function13.setName("TUVW");
			function13.setActive(false);
			functions.add(function13);

			/*
			 * FunctionJson function8 = new FunctionJson(); function8.setId(3012L);
			 * function8.setName("Chinese"); function8.setActive(false);
			 * functions.add(function8);
			 */
		}
		/*
		 * else if(screenId == 102){
		 * 
		 * functions = new ArrayList<FunctionJson>();
		 * 
		 * FunctionJson function1 = new FunctionJson(); function1.setId(3005L);
		 * function1.setName("English"); function1.setActive(false);
		 * functions.add(function1);
		 * 
		 * FunctionJson function2 = new FunctionJson(); function2.setId(3006L);
		 * function2.setName("French"); function2.setActive(false);
		 * functions.add(function2);
		 * 
		 * FunctionJson function3 = new FunctionJson(); function3.setId(3007L);
		 * function3.setName("Spanish"); function3.setActive(true);
		 * functions.add(function3);
		 * 
		 * FunctionJson function4 = new FunctionJson(); function4.setId(3008L);
		 * function4.setName("Arabic"); function4.setActive(false);
		 * functions.add(function4);
		 * 
		 * FunctionJson function5 = new FunctionJson(); function5.setId(3009L);
		 * function5.setName("Hindi"); function5.setActive(false);
		 * functions.add(function5);
		 * 
		 * FunctionJson function6 = new FunctionJson(); function6.setId(3010L);
		 * function6.setName("German"); function6.setActive(false);
		 * functions.add(function6);
		 * 
		 * FunctionJson function7 = new FunctionJson(); function7.setId(3011L);
		 * function7.setName("Russian"); function7.setActive(false);
		 * functions.add(function7);
		 * 
		 * FunctionJson function8 = new FunctionJson(); function8.setId(3012L);
		 * function8.setName("Chinese"); function8.setActive(false);
		 * functions.add(function8); }
		 */

		return functions;
	}

	//
	// private List<FunctionJson> fetchFunctionFromDatabase(int screenId) throws
	// Exception {
	//
	// // get the configuration set back from the database
	// List<ConfigurationNode> node =
	// this.configurationService.getAllConfigurations(0);
	//
	// FunctionJson function = new FunctionJson();
	// List<FunctionJson> functions = new ArrayList<FunctionJson>();
	//
	// function.setId(3001L);
	// function.setName("Redress Number");
	// function.setActive(false);
	// StationsAuditCriteriaJson auditCriteria = new StationsAuditCriteriaJson();
	// auditCriteria.setAllStations(true);
	//
	// List<AuditFieldJson> stations = new ArrayList<AuditFieldJson>();
	// AuditFieldJson station = new AuditFieldJson("ATL", false);
	// stations.add(station);
	// station = new AuditFieldJson("SEA", false);
	// stations.add(station);
	// station = new AuditFieldJson("MCO", false);
	// stations.add(station);
	// station = new AuditFieldJson("JFK", false);
	// stations.add(station);
	// auditCriteria.setStations(stations);
	//
	// function.setAuditCriteria(auditCriteria);
	// functions.add(function);
	// FunctionJson function2 = new FunctionJson();
	// function2.setId(3002L);
	// function2.setName("Known Travelers");
	// function2.setActive(true);
	// StationsAuditCriteriaJson auditCriteria1 = new StationsAuditCriteriaJson();
	// auditCriteria1.setAllStations(true);
	//
	// List<AuditFieldJson> stationsList = new ArrayList<AuditFieldJson>();
	// AuditFieldJson station1 = new AuditFieldJson("ABC", false);
	// stationsList.add(station1);
	// station1 = new AuditFieldJson("DEF", false);
	// stationsList.add(station1);
	// station1 = new AuditFieldJson("GHI", true);
	// stationsList.add(station1);
	// station1 = new AuditFieldJson("JKL", false);
	// stationsList.add(station1);
	// auditCriteria1.setStations(stationsList);
	//
	// function2.setAuditCriteria(auditCriteria1);
	//
	// functions.add(function2);
	// return functions;
	//
	// }

	public List<Rule> getRulesByScreenId(int screenId) {
		RuleJson rules = null;
		List<Rule> ruleList = new ArrayList<Rule>();
		if (screenId == 241 || screenId == 9999 || screenId == 10241 || screenId == 20241 || screenId == 30241) {
			rules = new RuleJson();
			rules.setRuleName("Mileage Plan");
			rules.setScreenName("Mileage Plan");
			rules.setDescription("Mileage Plan");

			// MM added related to load controls

			RuleControls ruleControls = new RuleControlsJson();
			ruleControls.setHasAddButton(true);
			ruleControls.setHasDeleteButton(false);
			ruleControls.setRuleType("MileageTable");

			TableDefinition tableDefinations = new TableDefinitionJson();
			RowSpecification rowSpecifications = new RowSpecificationJson();

			rowSpecifications.setRowName("Mileage Plan Program");
			rowSpecifications.setRowValue("Alaska Airline");
			// rowSpecifications.setRowStyle(style1);
			rowSpecifications.setRowWidget("TextBox");

			List<ColumnSpecification> colList = new ArrayList<ColumnSpecification>();
			AddColumnValues("Mileage Plan Code", "A5", colList, "TextBox");
			AddColumnValues("Allowed For Mileage Credit", "true", colList, "ON-OFF");
			AddColumnValues("Show Airline Name", "false", colList, "ON-OFF");
			RowSpecification rowSpecifications2 = new RowSpecificationJson();

			rowSpecifications2.setRowName("Mileage Plan Program");
			rowSpecifications2.setRowValue("Delta Airline");
			// rowSpecifications2.setRowStyle(style1);
			rowSpecifications2.setRowWidget("TextBox");

			List<ColumnSpecification> colList2 = new ArrayList<ColumnSpecification>();
			AddColumnValues("Mileage Plan Code", "A5", colList2, "TextBox");
			AddColumnValues("Allowed For Mileage Credit", "true", colList2, "ON-OFF");
			AddColumnValues("Show Airline Name", "false", colList2, "ON-OFF");

			rowSpecifications.setColSpecification(colList);
			rowSpecifications2.setColSpecification(colList2);
			List<RowSpecification> listRows = new ArrayList<RowSpecification>();
			listRows.add(rowSpecifications);
			listRows.add(rowSpecifications2);

			tableDefinations.setRowSpecification(listRows);
			tableDefinations.setRowCount(2);
			tableDefinations.setColumnCount(3);
			List<TableDefinition> listTables = new ArrayList<TableDefinition>();
			listTables.add(tableDefinations);
			rules.setTableDefinition(listTables);
			rules.setRuleControls(ruleControls);
		} else if (screenId == 244 || screenId == 10244 || screenId == 20244 || screenId == 30244) {
			rules = new RuleJson();
			rules.setRuleName("Special Service Requests (SSR) Code");
			rules.setScreenName("Special Service Requests Code");
			rules.setDescription("Special Service Requests (SSR) Code.");

			RuleControls ruleControls = new RuleControlsJson();
			ruleControls.setHasAddButton(true);
			ruleControls.setHasDeleteButton(true);
			ruleControls.setRuleType("CheckBoxTable");

			TableDefinitionJson tableDefinations = new TableDefinitionJson();

			RowSpecificationJson rowSpecifications = new RowSpecificationJson();

			List<ColumnSpecification> colList = new ArrayList<ColumnSpecification>();
			AddColumnValues("SSR", "PETC", colList, "TextBox");
			RowSpecificationJson rowSpecifications2 = new RowSpecificationJson();

			List<ColumnSpecification> colList2 = new ArrayList<ColumnSpecification>();
			AddColumnValues("SSR", "UMNR", colList2, "TextBox");
			RowSpecificationJson rowSpecifications3 = new RowSpecificationJson();

			List<ColumnSpecification> colList3 = new ArrayList<ColumnSpecification>();
			AddColumnValues("SSR", "BLND", colList3, "TextBox");

			rowSpecifications.setRowWidget("CheckBox");
			rowSpecifications2.setRowWidget("CheckBox");
			rowSpecifications3.setRowWidget("CheckBox");

			rowSpecifications.setColSpecification(colList);
			rowSpecifications2.setColSpecification(colList2);
			rowSpecifications3.setColSpecification(colList3);
			List<RowSpecification> listRows = new ArrayList<RowSpecification>();
			listRows.add(rowSpecifications);
			listRows.add(rowSpecifications2);
			listRows.add(rowSpecifications3);
			tableDefinations.setRowSpecification(listRows);
			tableDefinations.setRowCount(3);
			tableDefinations.setColumnCount(1);
			List<TableDefinition> listTables = new ArrayList<TableDefinition>();
			listTables.add(tableDefinations);
			rules.setTableDefinition(listTables);
			rules.setRuleControls(ruleControls);

		} else if (screenId == 444 || screenId == 10444 || screenId == 20444 || screenId == 30444) {
			rules = new RuleJson();
			rules.setRuleName("Offer");
			rules.setScreenName("Offer");

			RuleControls ruleControls = new RuleControlsJson();
			ruleControls.setHasAddButton(false);
			ruleControls.setHasDeleteButton(false);
			ruleControls.setRuleType("TableControl");

			TableDefinitionJson tableDefinations = new TableDefinitionJson();

			RowSpecificationJson rowSpecifications = new RowSpecificationJson();

			rowSpecifications.setRowName("Domestic");
			rowSpecifications.setRowValue("First Class");
			// rowSpecifications.setRowStyle(style1);
			rowSpecifications.setRowWidget("TextBox");

			List<ColumnSpecification> colList = new ArrayList<ColumnSpecification>();
			AddColumnValues("Exit Row", "$10", colList, "TextBox");
			AddColumnValues("Bulkhead", "$20", colList, "TextBox");
			AddColumnValues("Premium Cabin", "$60", colList, "TextBox");
			RowSpecificationJson rowSpecifications2 = new RowSpecificationJson();

			rowSpecifications2.setRowValue("Busssiness Class");
			rowSpecifications2.setRowName("Domestic");
			// rowSpecifications.setRowStyle(style1);
			rowSpecifications.setRowWidget("TextBox");

			List<ColumnSpecification> colList2 = new ArrayList<ColumnSpecification>();
			AddColumnValues("Exit Row", "$20", colList2, "TextBox");
			AddColumnValues("Bulkhead", "$40", colList2, "TextBox");
			AddColumnValues("Premium Cabin", "$90", colList2, "TextBox");

			rowSpecifications.setColSpecification(colList);
			rowSpecifications2.setColSpecification(colList2);
			List<RowSpecification> listRows = new ArrayList<RowSpecification>();
			listRows.add(rowSpecifications);
			listRows.add(rowSpecifications2);
			tableDefinations.setRowSpecification(listRows);
			tableDefinations.setRowCount(2);
			tableDefinations.setColumnCount(3);
			TableDefinitionJson tableDefinations2 = new TableDefinitionJson();

			RowSpecificationJson rowSpecifications21 = new RowSpecificationJson();

			rowSpecifications21.setRowValue("First Class");
			rowSpecifications21.setRowName("International");
			// rowSpecifications.setRowStyle(style1);
			rowSpecifications.setRowWidget("TextBox");

			List<ColumnSpecification> colList21 = new ArrayList<ColumnSpecification>();
			AddColumnValues("Exit Row", "$10", colList21, "TextBox");
			AddColumnValues("Bulkhead", "$20", colList21, "TextBox");
			AddColumnValues("Premium Cabin", "$60", colList21, "TextBox");
			RowSpecificationJson rowSpecifications221 = new RowSpecificationJson();

			rowSpecifications221.setRowValue("Busssiness Class");
			rowSpecifications221.setRowName("International");
			// rowSpecifications.setRowStyle(style1);
			rowSpecifications.setRowWidget("TextBox");

			List<ColumnSpecification> colList221 = new ArrayList<ColumnSpecification>();
			AddColumnValues("Exit Row", "$20", colList221, "TextBox");
			AddColumnValues("Bulkhead", "$40", colList221, "TextBox");
			AddColumnValues("Premium Cabin", "$90", colList221, "TextBox");
			rowSpecifications21.setColSpecification(colList21);
			rowSpecifications221.setColSpecification(colList221);
			List<RowSpecification> listRows21 = new ArrayList<RowSpecification>();
			listRows21.add(rowSpecifications21);
			listRows21.add(rowSpecifications221);
			tableDefinations2.setRowSpecification(listRows21);
			tableDefinations2.setRowCount(2);
			tableDefinations2.setColumnCount(3);
			List<TableDefinition> listTables21 = new ArrayList<TableDefinition>();
			listTables21.add(tableDefinations);
			listTables21.add(tableDefinations2);
			rules.setTableDefinition(listTables21);
			rules.setRuleControls(ruleControls);
		}

		ruleList.add(rules);
		return ruleList;
	}

	private void AddColumnValues(String columnName, Object columnValue, List<ColumnSpecification> listColSpec,
			String columnWidget) {
		ColumnSpecificationJson colSpecification = new ColumnSpecificationJson();
		colSpecification.setColumnName(columnName);
		colSpecification.setColumnValue(columnValue.toString());
		colSpecification.setColumnWidget(columnWidget);
		// colSpecification.setColumnStyle(columnStyle);
		listColSpec.add(colSpecification);
	}

	private void populateScreenNames() {
		screenNamesForGlobal = Arrays.asList("Logo", "Language Options", "Progress Bars", "Errors");
		screenIdsForGlobal = Arrays.asList(101, 102, 103, 104, 105);

		screenNamesForGlobalErrors = Arrays.asList("General Processing", "Find Reservation", "PNR Validation",
				"Passenger Selection", "Add FFN", "Seats", "Baggage", "Fees and Payment",
				"International Doc Collection", "Check-In");
		screenIdsForGlobalErrors = Arrays.asList(141, 142, 143, 144, 145,
				146, 147, 148, 149, 1410);

		screenNamesForBaseCheckIn = Arrays.asList("Admin Screen", "Attract Screen", "Find By Options",
				"Select Passenger", "Secure Flight", "Seat Assignment", "Baggage", "Thank You Screen",
				"Same Day Return", "Re-entry", "Re-entry & SDR Trip Selection", "Info Screen", "Error Messages");

		screenIdsForBaseCheckIn = Arrays.asList(201, 202, 203, 204, 205, 206,
				207, 208, 209, 2010, 2011, 2012, 2013);

		screenNamesForBaseCheckInSelectPassenger = Arrays.asList("Add Mileage Plan", "Add Infant",
				"Select Adult with Infant", "Special Service Requests Code", "Cities the Airline Flies to");
		screenIdsForBaseCheckInSelectPassenger = Arrays.asList(241, 242, 243, 244,
				245);

		screenNamesForBaseCheckInSecureFlight = Arrays.asList("Secure Flight Data Entry", "Secure Flight Data Review",
				"Secure Flight Privacy Notice");
		screenIdsForBaseCheckInSecureFlight = Arrays.asList(251, 252, 253);

		screenNamesForBaseCheckInBaggage = Arrays.asList("Baggage Check-In", "Special Items", "Baggage Weight/Scale",
				"Baggage Weight Advisory", "Baggage Security Questions", "Dangerous Goods", "Self Bag Tagging");
		screenIdsForBaseCheckInBaggage = Arrays.asList(271, 272, 273, 274, 275,
				276, 277);

		screenNamesForBaseCheckInThankYou = Arrays.asList("Thank You-1", "Thank You-2", "Thank You-3");
		screenIdsForBaseCheckInThankYou = Arrays.asList(278, 279, 280);

		screenNamesForInternationsDocEntry = Arrays.asList("Passport Review", "Passport Read", "Passport Expiration",
				"Passport Name Selection", "Manual Passport Entry - Step 1", "Manual Passport Entry - Step 2",
				"Country of Issue Selection", "Country of Residence - Prompt", "Country of Residence - Selection",
				"Country of Residence - Other", "Country of Residence - Step 2", "Resident Card",
				"Destination Address", "Emergency Contact", "Info Screens - 2 more");
		screenIdsForInternationsDocEntry = Arrays.asList(301, 302, 303, 304, 305,
				306, 307, 308, 309, 3010, 3011, 3012, 3013,
				3014, 3015);
		// More to be added in this
		screenNamesForFeeModule = Arrays.asList("Currency", "Baggage Fee", "Change Flight", "Premium Seating");
		screenIdsForFeeModule = Arrays.asList(401, 402, 403, 404, 405);

		screenNamesForFeeModuleBaggageFee = Arrays.asList("Baggage Fee - Piece", "Baggage Fee - Weight");
		screenIdsForFeeModuleBaggageFee = Arrays.asList(421, 422);

		screenNamesForFeeModulePremiumSeating = Arrays.asList("Seat Map with Fees", "Upgrade Option", "Fee Review",
				"Offer", "Payment - MultiPassenger", "Payment - Single Passenger", "Payment - No previous card used",
				"CC Swipe - Multi Passenger", "CC Swipe - Single Passenger");
		screenIdsForFeeModulePremiumSeating = Arrays.asList(441, 442, 443, 444, 445,
				446, 447, 448, 449);
		// More to be added in this
		screenNamesForNonRevenueModule = Arrays.asList("Attract Screen", "Find By Screens", "Passenger Selection",
				"Priority Selection", "NRPS Passenger Selection", "Seat Map - NRPS", "Thank You -NRSA",
				"Thank You - NRPS", "Info Screens");

		screenIdsForNonRevenueModule = Arrays.asList(501, 502, 503, 504, 505,
				506, 507, 508, 509);
		// More to be added in this
		screenNamesForAgentAssist = Arrays.asList("Agent ID", "Agent Password", "Agent Assist Find By",
				"Departure City Selection", "Flight Number Selection");
		screenIdsForAgentAssist = Arrays.asList(601, 602, 603, 604, 605);

	}

	private void populateProductCategories() {
		productCategories = new ArrayList<ProductCategory>();

		List<String> categoriesNameList = Arrays.asList("Global", "Base Check-in App", "International Doc Entry",
				"Fee Module", "Non Revenue Module", "Agent Assist Module");

		for (int counter = 0; counter <= 5; counter++) {

			ProductCategory productCategory = new ProductCategoryJson();
			productCategory.setName(categoriesNameList.get(counter));
			productCategory.setKey(categoriesNameList.get(counter));
			productCategory.setId(counter);
			List<Screen> screenList = null;
			switch (counter) {
			case 0:

				screenList = createScreens(screenNamesForGlobal, screenIdsForGlobal);

				List<Screen> childScreensForErrors = createScreens(screenNamesForGlobalErrors, screenIdsForGlobalErrors);
				Screen errorsScreen = screenList.get(3);

				// Add child screens for errors screen
				errorsScreen.setChildScreens(childScreensForErrors);
				productCategory.setScreens(screenList);
				break;
			case 1:
				screenList = createScreens(screenNamesForBaseCheckIn, screenIdsForBaseCheckIn);

				List<Screen> childScreensForSelectPassenger = createScreens(screenNamesForBaseCheckInSelectPassenger,
						screenIdsForBaseCheckInSelectPassenger);
				List<Screen> childScreensForSecureFlight = createScreens(screenNamesForBaseCheckInSecureFlight,
						screenIdsForBaseCheckInSecureFlight);
				List<Screen> childScreensForBaggage = createScreens(screenNamesForBaseCheckInBaggage,
						screenIdsForBaseCheckInBaggage);
				List<Screen> childScreensForThankYou = createScreens(screenNamesForBaseCheckInThankYou,
						screenIdsForBaseCheckInThankYou);

				Screen selectPassengerScreen = screenList.get(3);
				Screen secureFlightScreen = screenList.get(4);
				Screen BaggageScreen = screenList.get(6);
				Screen thankYouScreen = screenList.get(7);

				// Add child screens for select passenger screen
				selectPassengerScreen.setChildScreens(childScreensForSelectPassenger);

				// Add child screens for secure flight screen
				secureFlightScreen.setChildScreens(childScreensForSecureFlight);

				// Add child screens for baggage screen
				BaggageScreen.setChildScreens(childScreensForBaggage);
				thankYouScreen.setChildScreens(childScreensForThankYou);

				productCategory.setScreens(screenList);
				break;
			case 2:
				screenList = createScreens(screenNamesForInternationsDocEntry, screenIdsForInternationsDocEntry);
				productCategory.setScreens(screenList);
				break;
			case 3:
				screenList = createScreens(screenNamesForFeeModule, screenIdsForFeeModule);

				List<Screen> childScreensForBaggageFee = createScreens(screenNamesForFeeModuleBaggageFee,
						screenIdsForFeeModuleBaggageFee);
				List<Screen> childScreensForPremiumSeating = createScreens(screenNamesForFeeModulePremiumSeating,
						screenIdsForFeeModulePremiumSeating);

				Screen baggageFeeScreen = screenList.get(1);
				Screen premiumSeatingScreen = screenList.get(3);

				// Add child screens for select passenger screen
				baggageFeeScreen.setChildScreens(childScreensForBaggageFee);

				// Add child screens for secure flight screen
				premiumSeatingScreen.setChildScreens(childScreensForPremiumSeating);

				productCategory.setScreens(screenList);
				break;
			case 4:
				screenList = createScreens(screenNamesForNonRevenueModule, screenIdsForNonRevenueModule);
				productCategory.setScreens(screenList);
				break;
			case 5:
				screenList = createScreens(screenNamesForAgentAssist, screenIdsForAgentAssist);
				productCategory.setScreens(screenList);
				break;

			}
			productCategories.add(productCategory);

		}

	}
	
	public Integer lookupScreenId(String name) {
		
		for (Map.Entry<Integer, ScreenConfiguration> entries : screenConfigurations.entrySet()) {
			String screenConfigName = entries.getValue().getName();
			if (screenConfigName.equals(name)) {
				return entries.getValue().getId();
			}
		}
		return null;
	}

	private List<Screen> createScreens(List<String> listOfStrings, List<Integer> listOfIds) {
		List<Screen> screenList = new ArrayList<Screen>();

		for (int counterVar = 0; counterVar < listOfStrings.size(); counterVar++) {

			Screen tempScreen = new ScreenJson();
			tempScreen.setId(listOfIds.get(counterVar));
			tempScreen.setName(listOfStrings.get(counterVar));
			tempScreen.setKey(listOfStrings.get(counterVar));
			tempScreen.setChildScreens(null);
			screenList.add(tempScreen);
		}
		return screenList;
	}

	public List<Product> getProducts() {

		List<String> productsNameList = Arrays.asList("Kiosk Check-in", "Web Check-in", "Reservation/Ticketing",
				"Bag Drop");
		List<String> productsKeyList = Arrays.asList("KIOSK_CHECKIN", "WEB_CHECKIN", "RESERVATION_TICKETING",
		"BAG_DROP");

		List<ProductCategory> productCategories = getProductCategories();

		List<Product> products = new ArrayList<Product>();
		for (int i = 0; i < 4; i++) {
			Product product = new ProductJson();
			product.setName(productsNameList.get(i));
			product.setThemeId(PRODUCT_THEME_UUIDS.get(i));
			product.setKey(productsKeyList.get(i));
			product.setId(i);
			if (i == 0) {
				product.setCategories(productCategories);
			} else {
				product.setCategories(generateCategoriesForProducts(productCategories, product.getName()));
			}
			products.add(product);
		}
		return products;
	}

	public List<ProductCategory> getProductCategories() {
		return productCategories;
	}

	public void setProductCategories(List<ProductCategory> productCategories) {
		this.productCategories = productCategories;
	}

	private List<ProductCategory> generateCategoriesForProducts(List<ProductCategory> sourceCategories,
			String productName) {
		// Here multipler is used to set different ids for screens and
		// categories in different products
		int multiplier = 0;
		if (productName.equals("Kiosk Check-in")) {
			multiplier = MULTIPLIER_KIOSKCHECKIN;
		} else if (productName.equals("Web Check-in")) {
			multiplier = MULTIPLIER_WEBCHECKIN;
		} else if (productName.equals("Reservation/Ticketing")) {
			multiplier = MULTIPLIER_RESERVATION;
		} else if (productName.equals("Bag Drop")) {
			multiplier = MULTIPLIER_BAGDROP;
		}

		List<ProductCategory> productCategory = new ArrayList<ProductCategory>();
		for (ProductCategory sourceCategory : sourceCategories) {
			ProductCategory targetCategory = new ProductCategoryJson();
			targetCategory.setId(sourceCategory.getId() + (10 * multiplier));
			targetCategory.setName(sourceCategory.getName());
			targetCategory.setKey(sourceCategory.getName());
			List<Screen> sourceScreens = sourceCategory.getScreens();
			List<Screen> targetScreens = new ArrayList<Screen>();
			for (Screen sourceScreen : sourceScreens) {
				Screen targetScreen = new ScreenJson();
				targetScreen.setId(sourceScreen.getId() + multiplier);
				targetScreen.setName(sourceScreen.getName());
				targetScreen.setKey(sourceScreen.getName());
				targetScreens.add(targetScreen);
				List<Screen> sourceChildScreens = sourceScreen.getChildScreens();
				List<Screen> targetChildScreens = new ArrayList<Screen>();
				if (sourceChildScreens != null) {
					for (Screen sourceChildScreen : sourceChildScreens) {
						Screen targetChildScreen = new ScreenJson();
						targetChildScreen.setId(sourceChildScreen.getId() + multiplier);
						targetChildScreen.setName(sourceChildScreen.getName());
						targetChildScreen.setKey(sourceChildScreen.getName());
						targetChildScreens.add(targetChildScreen);
					}
					targetScreen.setChildScreens(targetChildScreens);
				}
			}
			targetCategory.setScreens(targetScreens);
			productCategory.add(targetCategory);
		}
		return productCategory;
	}

	public String initialize() throws Exception {

		ScreenConfiguration configuration = this.getScreenConfiguration(241);
		this.saveFunctions(configuration);
		//
		// String updatedBy = "Administrator";
		// Date updatedOn = new Date();
		//
		// //configuration sets for demo application code
		// Set<ConfigurationNode> nodes = new HashSet<ConfigurationNode>();
		//
		// //"Kiosk Check-in", "Web Check-in", "Reservation/Ticketing",
		// "Bag Drop"
		// ConfigurationNode checkin = new
		// ConfigurationNode(ConfigurationNodeTypeEnum.APPLICATION);
		// checkin.setName("Kiosk Check-in");
		// checkin.setDescription("Configuration set for Kiosk Check-in");
		// checkin.setUpdatedBy(updatedBy);
		// checkin.setUpdatedOn(updatedOn);
		//
		//
		//
		// ConfigurationNode webcheckin = new
		// ConfigurationNode(ConfigurationNodeTypeEnum.APPLICATION);
		// webcheckin.setName("WebCheckIn");
		// webcheckin.setDescription("Configuration set for Kiosk Check-in");
		// webcheckin.setUpdatedBy(updatedBy);
		// webcheckin.setUpdatedOn(updatedOn);
		//
		// ConfigurationNode reservation = new
		// ConfigurationNode(ConfigurationNodeTypeEnum.APPLICATION);
		// reservation.setName("Reservation");
		// reservation.setDescription("Configuration set for Reservation / Ticketing");
		// reservation.setUpdatedBy(updatedBy);
		// reservation.setUpdatedOn(updatedOn);
		//
		// ConfigurationNode bagdrop = new
		// ConfigurationNode(ConfigurationNodeTypeEnum.APPLICATION);
		// bagdrop.setName("BagDrop");
		// bagdrop.setDescription("Configuration set for Bag Drop application");
		// bagdrop.setUpdatedBy(updatedBy);
		// bagdrop.setUpdatedOn(updatedOn);
		//
		// nodes.add(checkin);
		// nodes.add(webcheckin);
		// nodes.add(reservation);
		// nodes.add(bagdrop);
		//
		// //add all the nodes
		// for(ConfigurationNode n : nodes){
		// this.configurationService.addConfiguration(n);
		// }

		return "Nodes added successfully";
	}

	public void saveFunctions(ScreenConfiguration screenConfiguration) throws Exception {

		// stream this list of functions back to disk
		saveFunctionsToDisk(screenConfiguration.getId(), screenConfiguration.getFunctions());
	}

	public void saveRules(ScreenConfiguration screenConfiguration) throws Exception {

		// stream this list of rules back to disk
		saveRulesToDisk(screenConfiguration.getId(), screenConfiguration.getRules());
	}

	public void saveText(ScreenConfiguration screenConfiguration) throws Exception {
		saveTextToDisk(screenConfiguration.getId(), screenConfiguration.getText());
	}

	private List<Function> fetchFunctionsFromDisk(int l) throws FileNotFoundException, IOException, Exception {

		// ensure the functions are on disk. create them if needed.
		this.ensureMockScreenFunctionDataExists(l);

		String fileName = this.createScreenFunctionFileName(l);

		// open the file and stream the objects back in
		FileInputStream inputStream;
		XMLDecoder in;

		// let's open the file.
		inputStream = new FileInputStream(fileName);
		in = new XMLDecoder(inputStream);

		// stream the objects in
		@SuppressWarnings("unchecked")
		List<Function> functions = (List<Function>) in.readObject();

		return functions;
	}

	private List<Text> fetchTextFromDisk(int screenId) throws FileNotFoundException, IOException, Exception {

		// ensure the text are on disk. create them if needed.
		this.ensureMockScreenTextDataExists(screenId);

		String fileName = this.createScreenTextFileName(screenId);

		// open the file and stream the objects back in
		FileInputStream inputStream;
		XMLDecoder in;

		// let's open the file.
		inputStream = new FileInputStream(fileName);
		in = new XMLDecoder(inputStream);

		// stream the objects in
		@SuppressWarnings("unchecked")
		List<Text> text = (List<Text>) in.readObject();

		return text;
	}

	private List<Rule> fetchRulesFromDisk(int l) throws FileNotFoundException, IOException, Exception {

		// ensure the functions are on disk. create them if needed.
		this.ensureMockScreenRuleDataExists(l);

		String fileName = this.createScreenRuleFileName(l);

		// open the file and stream the objects back in
		FileInputStream inputStream;
		XMLDecoder in;

		// let's open the file.
		inputStream = new FileInputStream(fileName);
		in = new XMLDecoder(inputStream);

		// stream the objects in
		@SuppressWarnings("unchecked")
		List<Rule> rules = (List<Rule>) in.readObject();

		return rules;
	}

	private void ensureMockScreenFunctionDataExists(int l) throws Exception, FileNotFoundException, IOException {

		String fileName;

		// create the file name based on screen id
		fileName = createScreenFunctionFileName(l);

		// create a file attribute object to tell us the state of the data file
		// we are looking for
		File findFile = new File(fileName);

		// do functions exist for this screen? If not, then use
		// mock function data code to generate seed set.
		if (findFile.exists() == false) {

			// get the list of mock functions
			List<Function> f;
			f = this.getMockScreenFunctions(l);

			saveFunctionsToDisk(l, f);

		}
	}

	private void ensureMockScreenTextDataExists(int screenId) throws Exception, FileNotFoundException, IOException {

		String fileName;

		// create the file name based on screen id
		fileName = createScreenTextFileName(screenId);

		// create a file attribute object to tell us the state of the data file
		// we are looking for
		File findFile = new File(fileName);

		// do text exist for this screen? If not, then use
		// mock text data code to generate seed set.
		if (findFile.exists() == false) {

			// get the list of mock text
			List<Text> text;
			text = this.getMockScreenText(screenId);

			logger.info("creating file: " + fileName + "screenId: " + screenId + ", text: " + text);
			saveTextToDisk(screenId, text);

		}
	}

	private void ensureMockScreenRuleDataExists(int l) throws Exception, FileNotFoundException, IOException {

		String fileName;

		// create the file name based on screen id
		fileName = createScreenRuleFileName(l);

		// create a file attribute object to tell us the state of the data file
		// we are looking for
		File findFile = new File(fileName);

		// do functions exist for this screen? If not, then use
		// mock function data code to generate seed set.
		if (findFile.exists() == false) {

			// get the list of mock functions
			List<Rule> f;
			f = this.getRulesByScreenId(l);

			saveRulesToDisk(l, f);

		}
	}

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger("Ezekiel");

	private void saveTextToDisk(int screenId, List<Text> textList) throws Exception {
		logger.info("Entered saveTextToDisk()");

		String fileName = createScreenTextFileName(screenId);
		int min = new Date().getMinutes();
		int secs = new Date().getSeconds();
		String debugStamp = "#" + min + ":" + secs;

		logger.info("Dumping text contents (screen " + screenId + ") before persistence " + textList);

		for (Text text : textList) {
			logger.info(this.convertToJsonString(text));
		}

		FileOutputStream outputStream;
		XMLEncoder out;

		// remove the existing file if it exists.
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}

		// stream functions out to a new functions file for this screen
		outputStream = new FileOutputStream(fileName);
		out = new XMLEncoder(outputStream);
		out.writeObject(textList);
		out.close();

		List<Text> saved = fetchTextFromDisk(screenId);
		logger.info("Retrieving text contents (screen " + screenId + ") after persistence");

		for (Text retrieved : saved) {
			logger.info(this.convertToJsonString(retrieved));
		}

	}

	private void saveRulesToDisk(int screenId, List<Rule> f) throws Exception {

		logger.info("Entered saveRulesToDisk()");

		String fileName = this.createScreenRuleFileName(screenId);

		int min = new Date().getMinutes();
		int secs = new Date().getSeconds();
		String debugStamp = "#" + min + ":" + secs;

		logger.info("Dumping function contents (screen " + screenId + ") before persistence");
		for (Rule rule : f) {
			// function.setName(function.getName()+ debugStamp);
			logger.info(this.convertToJsonString(rule));
		}

		FileOutputStream outputStream;
		XMLEncoder out;

		// remove the existing file if it exists.
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}

		// stream functions out to a new functions file for this screen
		outputStream = new FileOutputStream(fileName);
		out = new XMLEncoder(outputStream);
		out.writeObject(f);
		out.close();

		List<Rule> saved = this.fetchRulesFromDisk(screenId);
		logger.info("Retrieving function contents (screen " + screenId + ") after persistence");
		for (Rule retrieved : saved) {
			logger.info(this.convertToJsonString(retrieved));
		}
	}

	private void saveFunctionsToDisk(int screenId, List<Function> f) throws Exception {

		logger.info("Entered saveFunctionsToDisk()");

		String fileName = this.createScreenFunctionFileName(screenId);

		int min = new Date().getMinutes();
		int secs = new Date().getSeconds();
		String debugStamp = "#" + min + ":" + secs;

		logger.info("Dumping function contents (screen " + screenId + ") before persistence");
		for (Function function : f) {
			// function.setName(function.getName()+ debugStamp);
			logger.info(this.convertToJsonString(function));
		}

		FileOutputStream outputStream;
		XMLEncoder out;

		// remove the existing file if it exists.
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}

		// stream functions out to a new functions file for this screen
		outputStream = new FileOutputStream(fileName);
		out = new XMLEncoder(outputStream);
		out.writeObject(f);
		out.close();

		List<Function> saved = this.fetchFunctionsFromDisk(screenId);
		logger.info("Retrieving function contents (screen " + screenId + ") after persistence");
		for (Function retrieved : saved) {
			logger.info(this.convertToJsonString(retrieved));
		}
	}

	private String createScreenFunctionFileName(int l) {
		String fileName;
		fileName = "ScreenFunctions_" + l + ".xml";
		return fileName;
	}

	private String createScreenRuleFileName(int l) {
		String fileName;
		fileName = "ScreenRules_" + l + ".xml";
		return fileName;
	}

	private String createScreenTextFileName(int screenId) {
		String fileName;
		fileName = "ScreenText_" + screenId + ".xml";
		return fileName;
	}

	/**
	 * Converts the given object to json document
	 * 
	 * @param value
	 * @return
	 */
	private String convertToJsonString(Object value) {
		String result = value + "";
		if (mapper != null) {
			try {
				result = mapper.writeValueAsString(value);
			} catch (JsonGenerationException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param screenId
	 * @param graphicsId
	 * @param imageFile
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public void addImageToCollection(int screenId, int graphicsId, MultipartFile imageFile)
			throws IllegalStateException, IOException {

		String filePath = "";
		String imageUrl = "";
		int jdx;

		for (jdx = 0; jdx < this.screenGraphicsDictionary.get(screenId).size(); jdx++) {
			if (this.screenGraphicsDictionary.get(screenId).get(jdx).getId().equals(graphicsId)) {
				break;
			}

		}

		AvailableGraphicsJson newAvailableGraphics = new AvailableGraphicsJson();

		newAvailableGraphics.setSelected(false);

		if (screenId == 101) {
			filePath = this.imagesRootDirName + "\\Logo" + "\\" + imageFile.getOriginalFilename();

			imageUrl = this.logoImagesUrl + imageFile.getOriginalFilename();

		} else {
			String imageFolderName = this.screenGraphicsDictionary.get(screenId).get(jdx).getName();

			filePath = this.imagesRootDirName + "\\FindByOptions\\" + imageFolderName + "\\"
					+ imageFile.getOriginalFilename();

			imageUrl = this.findByOptionsImagesUrl + imageFolderName.toLowerCase() + "/"
					+ imageFile.getOriginalFilename();
		}

		newAvailableGraphics.setUrl(imageUrl);

		this.screenGraphicsDictionary.get(screenId).get(jdx).getAvailableGraphics().add(newAvailableGraphics);

		File f = new File(filePath);

		imageFile.transferTo(f);

	}

	/**
	 * @param screenId
	 * @param graphics
	 */
	public void updateGraphicsCollection(int screenId, List<Graphics> graphics) {
		// TODO Auto-generated method stub
		try {
			List<Graphics> graphicsCollection = this.screenGraphicsDictionary.get(screenId);

			for (Graphics graphics2 : graphicsCollection) {

				for (Graphics graphics3 : graphics) {

					if (graphics2.getId().equals(graphics3.getId())) {
						// Loop through each of the available graphics in
						// graphics item

						for (AvailableGraphics availableGraphics2 : graphics2.getAvailableGraphics()) {

							for (AvailableGraphics availableGraphics3 : graphics3.getAvailableGraphics()) {
								if (availableGraphics2.getUrl().equalsIgnoreCase(availableGraphics3.getUrl())) {
									availableGraphics2.setSelected(availableGraphics3.isSelected());
									break;
								}

							}
						}

						break;
					}

				}

			}

		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
